package GUI;

import util.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 资讯中心面板，用于展示绿色出行相关新闻和资讯
 */
public class NewsPanel extends JPanel {
    private User currentUser;
    private JPanel newsListPanel;
    private JComboBox<String> categoryComboBox;
    private List<NewsItem> newsItems = new ArrayList<>();

    // 模拟的新闻类别
    private String[] categories = {
            "全部资讯", "政策动态", "活动公告", "绿色出行", "环保科技", "低碳生活"
    };

    public NewsPanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);

        JLabel titleLabel = new JLabel("资讯中心", JLabel.LEFT);
        titleLabel.setFont(new Font("等线", Font.BOLD, 20));
        titleLabel.setForeground(new Color(0, 120, 0));
        titlePanel.add(titleLabel, BorderLayout.WEST);

        // 分类筛选
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        filterPanel.setOpaque(false);

        JLabel categoryLabel = new JLabel("分类:");
        categoryLabel.setFont(new Font("等线", Font.PLAIN, 14));
        filterPanel.add(categoryLabel);

        categoryComboBox = new JComboBox<>(categories);
        categoryComboBox.setFont(new Font("等线", Font.PLAIN, 14));
        categoryComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateNewsDisplay();
            }
        });
        filterPanel.add(categoryComboBox);

        JButton refreshButton = new JButton("刷新");
        refreshButton.setFont(new Font("等线", Font.PLAIN, 14));
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadNewsItems();
            }
        });
        filterPanel.add(refreshButton);

        titlePanel.add(filterPanel, BorderLayout.EAST);
        add(titlePanel, BorderLayout.NORTH);

        // 创建新闻列表面板
        createNewsListPanel();

        // 加载模拟新闻数据
        loadNewsItems();
    }

    /**
     * 创建新闻列表面板
     */
    private void createNewsListPanel() {
        // 主滚动面板
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 新闻列表面板
        newsListPanel = new JPanel();
        newsListPanel.setLayout(new BoxLayout(newsListPanel, BoxLayout.Y_AXIS));
        newsListPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        newsListPanel.setBackground(Color.WHITE);

        // 滚动面板设置
        JScrollPane scrollPane = new JScrollPane(newsListPanel);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220), 1));
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);

        // 始终显示垂直滚动条
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        // 设置滚动速度
        scrollPane.getVerticalScrollBar().setUnitIncrement(20);
        scrollPane.getVerticalScrollBar().setBlockIncrement(150);

        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 热门话题面板
        JPanel topicsPanel = createTopicsPanel();
        mainPanel.add(topicsPanel, BorderLayout.EAST);

        add(mainPanel, BorderLayout.CENTER);
    }

    /**
     * 创建热门话题面板
     */
    private JPanel createTopicsPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEmptyBorder(0, 10, 0, 0),
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1)));
        panel.setPreferredSize(new Dimension(250, getHeight()));
        panel.setBackground(new Color(250, 250, 250));

        JLabel topicsTitle = new JLabel("热门话题");
        topicsTitle.setFont(new Font("等线", Font.BOLD, 16));
        topicsTitle.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        topicsTitle.setAlignmentX(Component.LEFT_ALIGNMENT);
        panel.add(topicsTitle);

        // 热门话题列表
        String[] topics = {
                "碳中和目标对城市交通影响",
                "共享出行的未来发展趋势",
                "电动自行车新国标实施后评价",
                "公共交通系统数字化转型",
                "步行友好型城市建设进展",
                "绿色出行积分制度推广效果",
                "氢能源交通工具发展前景",
                "城市拥堵收费政策讨论",
                "自动驾驶公交系统试点情况"
        };

        for (String topic : topics) {
            JPanel topicItem = new JPanel(new BorderLayout());
            topicItem.setMaximumSize(new Dimension(250, 40));
            topicItem.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
            topicItem.setBackground(new Color(250, 250, 250));

            JLabel topicLabel = new JLabel(topic);
            topicLabel.setFont(new Font("等线", Font.PLAIN, 14));
            topicItem.add(topicLabel, BorderLayout.CENTER);

            JLabel viewsLabel = new JLabel(new Random().nextInt(10000) + "次浏览");
            viewsLabel.setFont(new Font("等线", Font.PLAIN, 12));
            viewsLabel.setForeground(Color.GRAY);
            topicItem.add(viewsLabel, BorderLayout.EAST);

            topicItem.setCursor(new Cursor(Cursor.HAND_CURSOR));
            topicItem.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    showNewsDetail("话题详情", topic, "这是关于" + topic + "的详细内容和讨论。此功能将在后续版本中完善。");
                }

                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    topicItem.setBackground(new Color(240, 245, 240));
                }

                public void mouseExited(java.awt.event.MouseEvent evt) {
                    topicItem.setBackground(new Color(250, 250, 250));
                }
            });

            panel.add(topicItem);
        }

        // 添加填充空间
        panel.add(Box.createVerticalGlue());

        return panel;
    }

    /**
     * 加载模拟的新闻数据
     */
    private void loadNewsItems() {
        newsItems.clear();

        // 添加一些模拟新闻
        newsItems.add(new NewsItem(
                "北京市发布绿色出行积分新政策",
                "政策动态",
                "北京市交通委员会近日发布新规定，鼓励市民使用公共交通和共享单车等绿色出行方式，参与者可获得碳积分奖励，用于兑换公交地铁优惠券和其他生活服务。",
                new Date(),
                "北京市交通委员会"));

        newsItems.add(new NewsItem(
                "2025年全国绿色出行日活动即将启动",
                "活动公告",
                "9月22日是全国绿色出行日，今年的主题是\"低碳交通，绿色发展\"，各地将举办骑行比赛、公交体验日等系列活动，鼓励公众参与绿色出行。",
                new Date(System.currentTimeMillis() - 86400000), // 前一天
                "中国环境保护部"));

        newsItems.add(new NewsItem(
                "新能源公交车占比已达75%，电动化转型加速",
                "绿色出行",
                "据交通运输部统计，截至2025年6月，全国公交车中新能源与清洁能源车辆占比已达75%，其中纯电动公交车超过50万辆，氢燃料电池公交车也开始在多地试点运营。",
                new Date(System.currentTimeMillis() - 172800000), // 前两天
                "交通运输部"));

        newsItems.add(new NewsItem(
                "智能网联单车将进入市场，配备自动避障系统",
                "环保科技",
                "多家共享单车企业宣布，将于年内推出新一代智能网联单车，配备自动避障系统、智能导航和健康监测功能，提升用户骑行体验和安全性。",
                new Date(System.currentTimeMillis() - 259200000), // 前三天
                "中国自行车协会"));

        newsItems.add(new NewsItem(
                "研究显示：绿色出行每年可减少碳排放2000万吨",
                "低碳生活",
                "中国社科院最新研究报告显示，如果全国城市居民绿色出行比例提高10%，每年可减少碳排放约2000万吨，相当于植树造林2亿棵。",
                new Date(System.currentTimeMillis() - 345600000), // 前四天
                "中国社会科学院"));

        newsItems.add(new NewsItem(
                "《城市步行和自行车交通系统规划设计导则》发布",
                "政策动态",
                "住建部联合交通运输部发布《城市步行和自行车交通系统规划设计导则》，要求新建道路必须配建自行车道和人行道，已建成道路将逐步改造，预计2025年基本建成绿色出行网络。",
                new Date(System.currentTimeMillis() - 432000000), // 前五天
                "住房和城乡建设部"));

        newsItems.add(new NewsItem(
                "全国多地启动无车日活动，限行范围扩大",
                "活动公告",
                "为响应世界无车日，全国多地将于9月22日实施部分区域机动车限行措施，并开展公共交通免费乘坐、共享单车免费骑行等活动，引导市民体验绿色出行方式。",
                new Date(System.currentTimeMillis() - 518400000), // 前六天
                "生态环境部"));

        newsItems.add(new NewsItem(
                "共享电动滑板车将在大学校园试点",
                "绿色出行",
                "继共享单车之后，共享电动滑板车将在全国多所大学校园试点运营，为校园内短距离出行提供更多选择。使用者通过手机APP可以随借随还，价格为每15分钟1元。",
                new Date(System.currentTimeMillis() - 604800000), // 前七天
                "教育部"));

        newsItems.add(new NewsItem(
                "新型超级电容公交车充电仅需30秒",
                "环保科技",
                "国内科研团队研发的新型超级电容公交车在多地试运行，该车型充电仅需30秒，续航可达10公里，特别适合短途高频次运行的城市公交线路。",
                new Date(System.currentTimeMillis() - 691200000), // 前八天
                "中国科学院"));

        newsItems.add(new NewsItem(
                "个人碳账户将与银行积分系统对接",
                "低碳生活",
                "多家银行宣布将与城市绿色出行平台对接，市民的绿色出行积分可兑换银行信用卡积分或直接折现，进一步提升参与绿色出行的积极性。",
                new Date(System.currentTimeMillis() - 777600000), // 前九天
                "中国银行业协会"));

        // 更新显示
        updateNewsDisplay();
    }

    /**
     * 根据筛选条件更新新闻显示
     */
    private void updateNewsDisplay() {
        newsListPanel.removeAll();

        String selectedCategory = (String) categoryComboBox.getSelectedItem();

        for (NewsItem item : newsItems) {
            if (selectedCategory.equals("全部资讯") || item.getCategory().equals(selectedCategory)) {
                // 创建单个新闻项
                JPanel newsItemPanel = createNewsItemPanel(item);
                newsListPanel.add(newsItemPanel);
                newsListPanel.add(Box.createVerticalStrut(10)); // 添加间隔
            }
        }

        newsListPanel.revalidate();
        newsListPanel.repaint();
    }

    /**
     * 创建单个新闻项面板
     */
    private JPanel createNewsItemPanel(NewsItem item) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout(10, 5));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230), 1, true),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));

        // 设置固定高度
        panel.setMinimumSize(new Dimension(0, 150));
        panel.setPreferredSize(new Dimension(getWidth(), 150));
        panel.setMaximumSize(new Dimension(Short.MAX_VALUE, 150));

        // 新闻标题
        JLabel titleLabel = new JLabel(item.getTitle());
        titleLabel.setFont(new Font("等线", Font.BOLD, 16));
        titleLabel.setForeground(new Color(50, 50, 50));

        // 类别标签
        JLabel categoryLabel = new JLabel(item.getCategory());
        categoryLabel.setFont(new Font("等线", Font.PLAIN, 12));
        categoryLabel.setForeground(Color.WHITE);
        categoryLabel.setOpaque(true);
        categoryLabel.setBackground(getCategoryColor(item.getCategory()));
        categoryLabel.setBorder(BorderFactory.createEmptyBorder(2, 8, 2, 8));

        // 标题面板（左侧标题右侧类别）
        JPanel titlePanel = new JPanel(new BorderLayout(10, 0));
        titlePanel.setOpaque(false);
        titlePanel.add(titleLabel, BorderLayout.CENTER);

        JPanel categoryPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        categoryPanel.setOpaque(false);
        categoryPanel.add(categoryLabel);
        titlePanel.add(categoryPanel, BorderLayout.EAST);

        panel.add(titlePanel, BorderLayout.NORTH);

        // 新闻摘要
        JLabel summaryLabel = new JLabel("<html><div style='width: 550px;'>" + item.getSummary() + "</div></html>");
        summaryLabel.setFont(new Font("等线", Font.PLAIN, 14));
        summaryLabel.setForeground(new Color(80, 80, 80));
        summaryLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        panel.add(summaryLabel, BorderLayout.CENTER);

        // 底部信息（发布日期和来源）
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setOpaque(false);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JLabel dateLabel = new JLabel(dateFormat.format(item.getPublishDate()));
        dateLabel.setFont(new Font("等线", Font.PLAIN, 12));
        dateLabel.setForeground(new Color(150, 150, 150));
        bottomPanel.add(dateLabel, BorderLayout.WEST);

        JLabel sourceLabel = new JLabel("来源: " + item.getSource());
        sourceLabel.setFont(new Font("等线", Font.PLAIN, 12));
        sourceLabel.setForeground(new Color(150, 150, 150));
        bottomPanel.add(sourceLabel, BorderLayout.EAST);

        panel.add(bottomPanel, BorderLayout.SOUTH);

        // 添加鼠标点击事件
        panel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        panel.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                showNewsDetail(item.getTitle(), item.getCategory(), item.getSummary());
            }

            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                panel.setBackground(new Color(248, 248, 248));
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                panel.setBackground(Color.WHITE);
            }
        });

        return panel;
    }

    /**
     * 根据分类获取对应的颜色
     */
    private Color getCategoryColor(String category) {
        switch (category) {
            case "政策动态":
                return new Color(0, 120, 215);
            case "活动公告":
                return new Color(231, 72, 86);
            case "绿色出行":
                return new Color(0, 150, 0);
            case "环保科技":
                return new Color(0, 130, 130);
            case "低碳生活":
                return new Color(209, 136, 33);
            default:
                return new Color(100, 100, 100);
        }
    }

    /**
     * 显示新闻详情
     */
    private void showNewsDetail(String title, String category, String content) {
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), title, true);
        dialog.setSize(600, 500);
        dialog.setLocationRelativeTo(this);

        JPanel contentPane = new JPanel(new BorderLayout(0, 10));
        contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题面板
        JPanel titlePanel = new JPanel(new BorderLayout(10, 0));
        titlePanel.setOpaque(false);

        JLabel categoryLabel = new JLabel(category);
        categoryLabel.setFont(new Font("等线", Font.BOLD, 12));
        categoryLabel.setForeground(Color.WHITE);
        categoryLabel.setOpaque(true);
        categoryLabel.setBackground(getCategoryColor(category));
        categoryLabel.setBorder(BorderFactory.createEmptyBorder(3, 8, 3, 8));
        titlePanel.add(categoryLabel, BorderLayout.WEST);

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("等线", Font.BOLD, 18));
        titlePanel.add(titleLabel, BorderLayout.CENTER);

        contentPane.add(titlePanel, BorderLayout.NORTH);

        // 内容
        JTextArea contentArea = new JTextArea(content);
        contentArea.setFont(new Font("等线", Font.PLAIN, 14));
        contentArea.setLineWrap(true);
        contentArea.setWrapStyleWord(true);
        contentArea.setEditable(false);
        contentArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JScrollPane scrollPane = new JScrollPane(contentArea);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220), 1));
        contentPane.add(scrollPane, BorderLayout.CENTER);

        // 关闭按钮
        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(closeButton);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setContentPane(contentPane);
        dialog.setVisible(true);
    }

    /**
     * 新闻项类
     */
    private class NewsItem {
        private String title;
        private String category;
        private String summary;
        private Date publishDate;
        private String source;

        public NewsItem(String title, String category, String summary, Date publishDate, String source) {
            this.title = title;
            this.category = category;
            this.summary = summary;
            this.publishDate = publishDate;
            this.source = source;
        }

        public String getTitle() {
            return title;
        }

        public String getCategory() {
            return category;
        }

        public String getSummary() {
            return summary;
        }

        public Date getPublishDate() {
            return publishDate;
        }

        public String getSource() {
            return source;
        }
    }
}